<template>
  <Modal
    title="新增用户"
    :value="visible"
    :mask-closable="false"   width="850"
    :closable="false"
  >

    <Spin>

      <Form ref="formValidate" :model="formValidate"    :rules="ruleValidate"  :label-width="80">
        <Row>
          <i-col  span="12">
            <FormItem label="用户名" prop="account">
              <Input  type="text"   v-model="formValidate.account" placeholder="请输入用户名" />
            </FormItem>
          </i-col>

          <i-col  span="12">
            <FormItem label="姓名" prop="name">
              <Input     v-model="formValidate.name" placeholder="请输入姓名" />
            </FormItem>
          </i-col>

          <i-col  span="12">
            <FormItem label="密码" prop="password">
              <Input   type="password"     v-model="formValidate.password" placeholder="请输入密码" />
            </FormItem>
          </i-col>

          <i-col  span="12">
            <FormItem label="确认密码" prop="confirmPassword">
              <Input  type="password"    v-model="formValidate.confirmPassword" placeholder="请再次输入密码" />
            </FormItem>
          </i-col>

          <i-col  span="12">
            <FormItem label="邮箱" prop="email">
              <Input     v-model="formValidate.email" placeholder="请输入邮箱" />
            </FormItem>
          </i-col>

          <i-col  span="12">
            <FormItem label="性别" prop="sex">
              <RadioGroup v-model="formValidate.sex" type="button">
                <Radio label="1" border>男</Radio>
                <Radio label="2" border>女</Radio>
              </RadioGroup>
            </FormItem>
          </i-col>

          <i-col  span="12">
            <FormItem label="部门" prop="deptid">
              <Select  v-model="formValidate.deptid" ref="select">
                <i-option v-for="item of list" :value="item.value" :key="item.value" style="display: none;">
                  {{ item.name }}
                </i-option>
                <Tree :data="loadData"  ref="deptTree"   @on-select-change="handleCheckChange" :show-checkbox="false" :multiple="false" ></Tree>
              </Select>
            </FormItem>
          </i-col>
        </Row>

      </Form>
    </Spin>
    <div slot="footer" ref="footer">
      <Button   @click="cancel('formValidate')">取消</Button>
      <Button type="primary" @click="submit('formValidate')">确定</Button>
    </div>
  </Modal>

</template>

<script>
    import {getDeptTree,userAdd} from '@/api/userList';
    import  TreeSelect from  '_c/tree-select';

    export default {
        name: "UserAdd",
        components:{
            TreeSelect
        },
        computed:{

        },
        data(){
           const  validatePassword =  (rule,value,callback)=> {
                //var reg  = /^[a-zA-Z0-9]{6-10}$/;
                if(value ===''){
                    callback(new Error('请输入密码'))
                }/*else if(new RegExp(reg).test(value) ===false){
                    callback(new Error("无效的密码"));
                }*/else{
                    callback();
                }
            };
           const  validateCheckPassword = (rule,value,callback)=> {
                if(value ===''){
                    callback(new Error('请输入确认密码'))
                }else if(value !== this.formValidate.password){
                    callback(new Error('两次输入的密码不一致'))
                }else{
                    callback();
                }
            };
            return {
                visible:false,
                list:[],
                formValidate: {
                    account: '',
                    password:'',
                    confirmPassword:'',
                    name:'',
                    email:'',
                    sex:'',
                    deptid:'',
                },ruleValidate: {
                    account: [
                        { required: true, message: '用户名不能为空', trigger: 'blur' },
                        { type: 'string',  min: 5,max: 12, message: '用户名长度 5-12个字符', trigger: 'blur' },
                        //{ pattern: /^[a-zA-Z0-9]$/, message: '大小写字母及数据组成', trigger: 'blur' },
                    ],
                    name: [
                        { required: true, message: '姓名不能为空', trigger: 'blur' },
                        { type: 'string',  min: 2,max: 12, message: '姓名长度 2-12个字符', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '邮箱不能为空', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
                    ],
                    password: [
                        {required: true, validator:validatePassword, trigger: 'blur' }
                    ],
                    confirmPassword: [
                        { required: true,validator:validateCheckPassword, trigger: 'click' }
                    ],
                    sex: [
                        { required: true, message: '请选择性别', trigger: 'click' }
                    ],
                    deptid: [
                        { required: true,type: 'string', message: '请选择部门', trigger: 'change' }
                    ]
                },
                // 加载数据方法 必须为 Promise 对象
                loadData: [],
            }
        },
        mounted(){
            getDeptTree()
                .then(res => {
                    //console.log(res)
                    this.loadData =  res.data;
                    let value = '';
                    let name = '';
                    let this1 = this;
                    res.data.forEach((item, index) => {
                        value =`${item.id}`
                        name = `${item.name}`
                        this1.list.push({
                            value,
                            name
                        });
                        if(item.children){
                            item.children.forEach((children)=>{
                                value =`${children.id}`
                                name = `${children.name}`
                                this1.list.push({
                                    value,
                                    name
                                })
                            });
                        }

                    })
                    console.log(this1.list)
                }).catch(function (error) {
                console.log(error+"用户部门树加载失败");
            })
        },
        methods:{
            add () {
                this.visible = true
            },
            handleCheckChange (data) {
                let value = ''
                let name = ''
                data.forEach((item, index) => {
                        value =`${item.id}`
                        name = `${item.name}`
                })
               this.formValidate.deptid = value;
                this.$refs.footer.click();
            },
            submit(name){
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        debugger
                        userAdd(this.formValidate).then(res=>{
                              if(res.data.code ===200){
                                  this.$Message.success({
                                      content: '添加成功',
                                      duration: 3,
                                      closable: true
                                      }
                                  );
                                  this.resetFiled(name);
                                  this.visible = false
                                  this.$emit('ok')
                              }else{
                                  this.$Message.error({
                                          content: res.data.message,
                                          duration: 3,
                                          closable: true
                                      }
                                  );
                              }
                        }).catch(function (error) {
                            console.log("添加用户失败");
                        });
                    } else {
                        return;
                    }
                });

            },
            resetFiled(name){
                this.$refs[name].resetFields();
                this.visible = false;
                let  node =  this.$refs.deptTree.getSelectedNodes();
                node.forEach((item) => {
                    item.selected = false;
                });

                let arr = this.$refs.deptTree.stateTree;
                arr.forEach((item)=>{
                    console.log(item.expand)
                    item.expand = false;
                })
                return ;
            },
            cancel(name){
                this.resetFiled(name);
            }
        }
    }
</script>

<style lan="stylus" rel="stylesheet/stylus">

</style>
